package root.electronclass.electronclass

import android.app.Application
import android.util.Log
import com.blankj.utilcode.util.LogUtils
import root.electronclass.electronclass.common.util.GlideCacheUtil
import root.electronclass.electronclass.mvp.GlobalParameter
import root.electronclass.electronclass.other.DeviceCodeActivity
import com.facebook.drawee.backends.pipeline.Fresco
import com.tencent.bugly.crashreport.CrashReport
import com.tencent.smtt.sdk.QbSdk
import com.tencent.smtt.sdk.QbSdk.PreInitCallback
import com.tencent.upgrade.bean.UpgradeConfig
import com.tencent.upgrade.core.UpgradeManager
import io.reactivex.plugins.RxJavaPlugins
import me.goldze.mvvmhabit.crash.CaocConfig
import android.os.Build

class App : Application() {

    companion object {
        lateinit var app:App
    }
    override fun onCreate() {
        super.onCreate()
        app = this
        Fresco.initialize(this)
        RxJavaPlugins.setErrorHandler { t -> t.printStackTrace() }
        LogUtils.getConfig().setSingleTagSwitch(false)
        val strategy = CrashReport.UserStrategy(this)
        strategy.deviceID = GlobalParameter.getDeviceCode()
        CrashReport.initCrashReport(applicationContext, "c4ab9b0fd3", false);

        //检测程序崩溃
        CaocConfig.Builder.create()
            .backgroundMode(CaocConfig.BACKGROUND_MODE_SILENT) //背景模式,开启沉浸式
            .enabled(true) //是否启动全局异常捕获
            .showErrorDetails(true) //是否显示错误详细信息
            .showRestartButton(true) //是否显示重启按钮
            .trackActivities(true) //是否跟踪Activity
            .minTimeBetweenCrashesMs(2000) //崩溃的间隔时间(毫秒)
            .errorDrawable(R.mipmap.ic_launcher) //错误图标
            .restartActivity(DeviceCodeActivity::class.java) //重新启动后的activity
            .apply()

        GlideCacheUtil.getInstance().clearImageAllCache(this)
        val imagePipeline = Fresco.getImagePipeline()
        imagePipeline.clearCaches()
        initX5WebView()
        val builder: UpgradeConfig.Builder = UpgradeConfig.Builder()
        val config = builder.appId("469c2917ca").appKey("38ccea42-3c70-4aa4-ae91-f36337ae9396").build()
        UpgradeManager.getInstance().init(this, config)
    }

    private fun initX5WebView() { //搜集本地tbs内核信息并上报服务器，服务器返回结果决定使用哪个内核。
        val cb: PreInitCallback = object : PreInitCallback {
            override fun onViewInitFinished(arg0: Boolean) { //x5內核初始化完成的回调，为true表示x5内核加载成功，否则表示x5内核加载失败，会自动切换到系统内核。
                if (arg0) {
                    Log.e("=====myApp", " x5WebView内核加载成功$arg0")
                } else {
                    Log.e("=====myApp", " x5WebView内核加载失败$arg0")
                }
            }

            override fun onCoreInitFinished() {}
        } //x5内核初始化接口
        QbSdk.initX5Environment(applicationContext, cb)
    }
}